//
//  FSLTitleView.swift
//  FSLText
//
//  Created by 我演示 on 2019/11/2.
//  Copyright © 2019 ALLSall. All rights reserved.
//

import UIKit


protocol FSLPageTitleViewDelegate : class  {
    func pageView(_ pageView: FSLTitleView , targetIndex: Int)
}


class FSLTitleView: UIView {
    
    weak var delegate : FSLPageTitleViewDelegate?
    
    var titles:[String]
    var style : FSLTitleStyle
    private lazy var titleLabels : [UILabel] = [UILabel]()
    fileprivate lazy var currentIndex : Int = 0
    
    /**创建scrollview*/
    fileprivate lazy var scrollView : UIScrollView = {
    let scrollView = UIScrollView(frame: self.bounds)
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.scrollsToTop = false
        return scrollView
    }()
    
    /// 滚动条
    fileprivate lazy var bottomLine : UIView = {
        let bottomLine = UIView()
        bottomLine.backgroundColor = self.style.scrollLineColor
        bottomLine.frame.size.height = self.style.scrollLineHeight
        bottomLine.frame.origin.y = 0 ;
        
        return bottomLine
    }()
    
    
    init(frame: CGRect , titles: [String] , style : FSLTitleStyle) {
        self.titles = titles
        self.style = style
        super.init(frame: frame)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
extension FSLTitleView {
    fileprivate func setUpUI () {
        //1: 添加scrlllvew
        addSubview(scrollView)
        
        //2: 讲titleLabel 添加到UIscrollow
        setUpTtitleLabels()
        
        //3: 设置titleLabel的frame
       setupTitleLablesFrame()
        
        
        //4: 添加滚动条信息
        if style.isShowScrollLine {
            scrollView.addSubview(bottomLine)
        }

    }
    
    private func setUpTtitleLabels() {
        for (i , title) in titles.enumerated() {
            let titlelabel = UILabel()
            titlelabel.text = title
            titlelabel.textColor = i == 0 ? style.selectedColor : style.normalColor
            titlelabel.textAlignment = .center
            titlelabel.font = UIFont.systemFont(ofSize: style.fonSize)
            
            scrollView.addSubview(titlelabel)
            titleLabels.append(titlelabel)
            
            let tap =  UITapGestureRecognizer.init(target: self, action: #selector(titleLabelClick(_:)))
            titlelabel.addGestureRecognizer(tap)
            titlelabel.isUserInteractionEnabled = true
          
            
            
            
        }
        }
    /// 设置对应f的frame 信息
    
    private  func setupTitleLablesFrame() {
        
        let count = titles.count
        for (i , label) in titleLabels.enumerated() {
            var w : CGFloat = 0
            let h : CGFloat = 0
            var x :CGFloat = 0
            let y : CGFloat = 0
            if  style.isScrollEnable {
                w =    (titles[i] as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : label.font as Any], context: nil).width
        
                if i == 0 {
                    x = style.itemMargin * 0.5
                    if style.isShowScrollLine {
                        bottomLine.frame.origin.x = 0
                        bottomLine.frame.size.width = w
                    }
                    
                } else {
                    x = titleLabels[i - 1].frame.maxX + style.itemMargin
                }
                
            }else {
                w = bounds.width / CGFloat(count)
                x = w  * CGFloat(i)
                bottomLine.frame.origin.x = 0
                bottomLine.frame.size.width = w
            }
            
            label.frame =  CGRect(x: x , y: y , width: w , height: h)
            
        }
        
        
        scrollView.contentSize = style.isScrollEnable ? CGSize(width: titleLabels.last!.frame.maxX + style.itemMargin * 0.5, height: 0) : CGSize.zero
        
        
    }
    
}

// MARK:  添加对应的收拾信息
extension FSLTitleView {
    @objc fileprivate func titleLabelClick (_ tap : UITapGestureRecognizer) {
        
        //1: 取出用户点击的view
        let targetLabel = tap.view as! UILabel
  
        // 调整title
        adjustTitleLabel(targetIndex: targetLabel.tag)
        
        //3:调整bottomLine
        if style.isShowScrollLine {
            UIView.animate(withDuration: 0.25) {
                self.bottomLine.frame.origin.x = targetLabel.frame.origin.x
                self.bottomLine.frame.size.width =  targetLabel.frame.size.width
                
            }
        }

        
        //2: 通知代理
     delegate?.pageView(self, targetIndex: currentIndex)
              
    }
    
    fileprivate func adjustTitleLabel(targetIndex : Int )  {
        
        if targetIndex == currentIndex {return}
        
        //1: 取出label
        let targetLabel = titleLabels[targetIndex]
        let sourceLabel = titleLabels[currentIndex]
        
        //2:切换颜色
        targetLabel.textColor = style.selectedColor
        sourceLabel.textColor = style.normalColor
        
        ///3:记录下标值
        currentIndex = targetIndex
        
        // 4:通知contentView 进行调整
        delegate?.pageView(self, targetIndex: currentIndex)
        
        //5: 内容滚动视图，调整位置
        
        //4:  调整位置
        if style.isScrollEnable {
            var  ofsetX = targetLabel.center.x - scrollView.bounds.width * 0.5
            
            ///1： 不需要居中
            if ofsetX < 0 {
                ofsetX = 0
            }
            ///2: 不需要居中
            if  ofsetX > scrollView.contentSize.width - scrollView.bounds.width {
                ofsetX = scrollView.contentSize.width  -  scrollView.bounds.width
            }
            scrollView.setContentOffset(CGPoint(x: ofsetX, y: 0) , animated: true)
        }
    }
    
}


///3: 遵守对应的协议和代理
extension FSLTitleView : FSLContentViewDelegate {
    func contentView(_ contentView: FSLContentView, targetIndex: Int, progress: CGFloat) {
        // 1: 取出label
        let targetLabel = titleLabels[targetIndex]
        let sourceLabel = titleLabels[currentIndex]
        
        //2: 颜色渐变
        let deletaRGB = UIColor.getRGBDelta(firstColor: style.selectedColor, secondColor: style.normalColor)
        let  selectedRGB = style.selectedColor.getRGB()
        let normalRGB = style.normalColor.getRGB()
        
//        targetLabel.textColor = UIColor(red: normalRGB.0 + deletaRGB.0*progress, green: normalRGB.1 + deletaRGB.1 + deletaRGB  *  progress, blue: normalRGB.2 + deletaRGB.2*progress, alpha: 1)
//        
//        sourceLabel.textColor = UIColor(red: normalRGB.0 - deletaRGB.0*progress, green: normalRGB.1 - deletaRGB.1 - deletaRGB * progress, blue: normalRGB.2 - deletaRGB.2*progress, alpha: 1)
        
        if style.isShowScrollLine {
            
        }
    }
  
    
    func contentView(_ contentView: FSLContentView, targetIndex: Int) {
        adjustTitleLabel(targetIndex: targetIndex)
    }
}


